package com.pw.lit.controller;

import com.pw.lit.bean.Diary;
import com.pw.lit.bean.DiaryExample;
import com.pw.lit.bean.User;
import com.pw.lit.service.DiaryService;
import com.pw.lit.service.MessageService;
import com.pw.lit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/Diary")
public class DiaryController {

    @Autowired
    private DiaryService diaryService;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;

    //日记首页
    @RequestMapping("/diaryindex")
    public String diaryindex(Model model) {
        System.out.println("日记首页");
        List<Diary> diaries = getdiary();
        List<User> users = getuser(diaries);
        model.addAttribute("diaries", diaries);
        model.addAttribute("users", users);

        return "FrontPages/diary/diary-index";
    }

    public List<Diary> getdiary() {
        DiaryExample example = new DiaryExample();
        DiaryExample.Criteria criteria = example.createCriteria();
        criteria.andDidIsNotNull();
        criteria.andOpenedEqualTo("1");
        example.setOrderByClause("Did desc");
        return diaryService.selectByExample(example);
    }

    public List<User> getuser(List<Diary> list) {
        List<User> users = new ArrayList<>();
        for (Diary d : list) {
            users.add(userService.selectByPrimaryKey(d.getId()));
        }
        return users;
    }

    //分页
    @RequestMapping("/diarylist")
    @ResponseBody
    public Map<String, Object> diarylist(@RequestParam("limit") String limit,
                                         @RequestParam("page") String page) {
        Map<String, Object> map = new HashMap<>();
        List<Diary> diaryList = pages(getdiary(), Integer.parseInt(limit), Integer.parseInt(page));
        List<User> userList = getuser(diaryList);
//        map.put("count",getdiary());
        map.put("diaries", diaryList);
        map.put("users", userList);
        return map;
    }

    //分页方法
    public <E> List<E> pages(List<E> list, int limit, int start) {
//        System.out.println(limit + "分页" + start + "总数" + list.size());
        List<E> nowList = new ArrayList<E>();
        int num = limit * start;
        if (num - limit <= list.size()) {
            for (int i = num - limit; i < list.size() && i < num; i++) {
                nowList.add(list.get(i));
            }
        } else {
            for (int i = start - 1; i < list.size(); i++) {
                nowList.add(list.get(i));
            }
        }
        return nowList;
    }

    //我的日记
    @RequestMapping("/diaryedit")
    public String diaryedit(HttpSession session,
                            Model model) {
        User u = (User) session.getAttribute("user");
        model.addAttribute("diaries", getDiary(u.getId(), "1"));
        model.addAttribute("num1", getDiary(u.getId(), "1").size());
        model.addAttribute("num2", getDiary(u.getId(), "0").size());
        return "FrontPages/diary/diary-edit";
    }

    //获取日记列表
    public List<Diary> getDiary(int id, String type) {
        DiaryExample example = new DiaryExample();
        DiaryExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        criteria.andOpenedEqualTo(type);
        try {
            List<Diary> diaries = diaryService.selectByExample(example);
            diaries.sort(Comparator.comparing(Diary::getDid).reversed());
            return diaries;
        } catch (Exception e) {
            return null;
        }
    }

    @RequestMapping("/opened/{op}")
    @ResponseBody
    public Map<String, Object> opened(HttpSession session,
                                        @PathVariable("op") String op) {
        Map<String, Object> map = new HashMap<>();
        User u = (User) session.getAttribute("user");
        map.put("diaries", getDiary(u.getId(), op));
        if (op.equals("1")) {
            map.put("op", "设为私密");
        } else {
            map.put("op", "设为公开");
        }
        return map;
    }

    //发布日记
    @RequestMapping("/diaryrelease")
    @ResponseBody
    public Map<String, Object> diaryrelease(HttpSession session,
                                            @RequestParam("content") String content,
                                            @RequestParam("op") String op) {
        Map<String, Object> map = new HashMap<>();
        User u = (User) session.getAttribute("user");
        Diary diary = new Diary();
        diary.setId(u.getId());
        diary.setContent(content);
        diary.setOpened(op);
        diary.setDate(gettime());
        diary.setLikeNumber(0);
        diary.setBrowseNumber(0);
        try {
            diaryService.insert(diary);
            map.put("msg", "发表成功!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "发表失败!");
        }
        return map;
    }

    //日记详情
    @RequestMapping("/diarydetail/{type}/{did}")
    public String diarydetail(Model model, @PathVariable("type") String type,
                              @PathVariable("did") String did) {
        Diary diary = diaryService.selectByPrimaryKey(Integer.parseInt(did));
        User user = userService.selectByPrimaryKey(diary.getId());
        model.addAttribute("diary", diary);
        model.addAttribute("user", user);
        if (type.equals("y")) {
            model.addAttribute("type", "y");
        } else {
            model.addAttribute("type", "n");
        }
        return "FrontPages/diary/diary-detail";
    }

    //点赞
    @RequestMapping("/setzan/{type}/{did}")
    @ResponseBody
    public void setzan(@PathVariable("type") String type,
                       @PathVariable("did") String did) {
        Diary diary = diaryService.selectByPrimaryKey(Integer.parseInt(did));
        if (type.equals("1")) {
            diary.setLikeNumber(diary.getLikeNumber() + 1);
        } else {
            diary.setLikeNumber(diary.getLikeNumber() - 1);
        }
        try {
            diaryService.updateByPrimaryKey(diary);
            System.out.println("日记点赞");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //修改日记
    @RequestMapping("/updatediary")
    @ResponseBody
    public Map<String, Object> updatediary(@RequestParam("did") String did,
                                           @RequestParam("content") String content,
                                           @RequestParam("op") String op) {
        Map<String, Object> map = new HashMap<>();
        Diary diary = diaryService.selectByPrimaryKey(Integer.parseInt(did));
        diary.setContent(content);
        diary.setOpened(op);
        try {
            diaryService.updateByPrimaryKey(diary);
            map.put("msg", "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "修改失败!");
        }
        return map;
    }

    //删除日记
    @RequestMapping("/deldiary/{did}")
    @ResponseBody
    public Map<String, Object> deldiary(HttpSession session,
                                        @PathVariable("did") String did) {
        Map<String, Object> map = new HashMap<>();
        User u = (User) session.getAttribute("user");
        try {
            diaryService.deleteByPrimaryKey(Integer.parseInt(did));
            map.put("num1", getDiary(u.getId(), "1").size());
            map.put("num2", getDiary(u.getId(), "0").size());
            map.put("msg", "删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "删除失败!");
        }
        return map;
    }

    //设为公开-私密
    @RequestMapping("/changeop")
    @ResponseBody
    public Map<String, Object> changeop(@RequestParam("did") String did,
                                        @RequestParam("op") String op) {
        Map<String, Object> map = new HashMap<>();
        Diary diary = diaryService.selectByPrimaryKey(Integer.parseInt(did));
        if (op.equals("设为公开")) {
            diary.setOpened("1");
        } else {
            diary.setOpened("0");
        }
        try {
            diaryService.updateByPrimaryKey(diary);
            map.put("msg", "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "修改失败!");
        }
        return map;
    }

    //获取当前时间
    public String gettime() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String time = sdf.format(date);
        return time;
    }
}
